//
//  SavePlantSetTableViewController.m
//  PlotMate
//
//  Created by Brian Boyle on 01/04/2012.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "SavePlantSetTableViewController.h"
#import "PlantSet+CRUD.h"
#import "Plant+CRUD.h"
#import "Plant.h"
#import "AppDelegate.h"
#import "UITableViewCell+TextFont.h"


@interface SavePlantSetTableViewController()

@property (nonatomic, strong) NSMutableArray *plantsArray;
@property (nonatomic, strong) NSManagedObjectContext *context;
@property (nonatomic, strong) NSArray *existingPlantSetsArray;
@property (nonatomic, strong) PlantSet *selectedPlantSet;
-(UITextField *)getNameTextField;

@end


@implementation SavePlantSetTableViewController
@synthesize plantsArray = plantsArray;
@synthesize context = _context;

@synthesize addtoExistingPlantSet = _addtoExistingPlantSet;
@synthesize existingPlantSetsArray = _existingPlantSetsArray;
@synthesize selectedPlantSet = _selectedPlantSet;

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    //Get the managedObjectContext from the AppDeletgate
    self.context = [(AppDelegate*)[UIApplication sharedApplication].delegate managedObjectContext];

    //Get the list of plants in a set from the NSUserDefaults
    NSArray *plantNames = [PlantSet getPlantSetFromNSUserDefaults];
    self.plantsArray = [[Plant loadAllPlantsInArray:plantNames withContext:self.context] mutableCopy];
    
    if(self.addtoExistingPlantSet == YES){
        self.existingPlantSetsArray = [PlantSet getAllPlantSetsInContext:self.context];
    }
    
    //Set the background image
    UIImageView *tempImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"paper.png"]];
    [tempImageView setFrame:self.tableView.frame]; 
    self.tableView.backgroundView = tempImageView;
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tableView setEditing:YES];
    
    //Check if we are adding to an existing PlantSet or creating a new one. Change UI elements based on that.
    if(self.addtoExistingPlantSet == NO){
        //Disable the Save button until text is entered into the name field.
        [self.navigationItem.rightBarButtonItem setEnabled:NO];
    }else{
        UITableViewCell *pickerCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
        UIPickerView *picker = (UIPickerView *)[pickerCell viewWithTag:1];
        int currentRow = [picker selectedRowInComponent:0];
        self.selectedPlantSet = [self.existingPlantSetsArray objectAtIndex:currentRow];
    }
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self getNameTextField].delegate = self;
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0 && self.addtoExistingPlantSet == YES){
        return 185;
    }
    return 44;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 0){
        return 1;
    }
    return [self.plantsArray count];
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0){
        return NO;
    }
    return YES;
}

-(UITableViewCell *)buildSetPickerCellForTableView:(UITableView *)tableView AtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"setPickerCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    UIPickerView *pickerView = (UIPickerView *)[cell viewWithTag:1];
    pickerView.frame = CGRectMake(pickerView.frame.origin.x, pickerView.frame.origin.y, pickerView.frame.size.width, 200);
    //Make the cell transparent with no border
    cell.backgroundView = [[UIView alloc] initWithFrame:CGRectZero];
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}

-(UITableViewCell *)buildNameCellForTableView:(UITableView *)tableView AtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"nameCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    //Make the cell transparent with no border
    cell.backgroundView = [[UIView alloc] initWithFrame:CGRectZero];
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}

-(UITableViewCell *)buildPlantCellForTableView:(UITableView *)tableView AtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"plantInSet";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    Plant *plant = [self.plantsArray objectAtIndex:indexPath.row];
    cell.textLabel.text = plant.name;
    [cell setSketchBlockFont];
    cell.imageView.image = [UIImage imageNamed:[plant.name stringByAppendingString:@"_S"]];
    //Make the cell transparent with no border
    cell.backgroundView = [[UIView alloc] initWithFrame:CGRectZero];
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0){
        //Check if we are adding to an existing set or creating a new one
        if(self.addtoExistingPlantSet == YES){
            return [self buildSetPickerCellForTableView:tableView AtIndexPath:indexPath];
        }else{
            return [self buildNameCellForTableView:tableView AtIndexPath:indexPath];
        }
    }else{
        return [self buildPlantCellForTableView:tableView AtIndexPath:indexPath];
    }
}


// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        //Delete plant name from the NSUserDefaults and the plant object from the local array
        Plant *plantToBeDeleted = [self.plantsArray objectAtIndex:indexPath.row];
        [PlantSet deletePlantNameFromNSUserDefaults:plantToBeDeleted.name];
        [self.plantsArray removeObject:plantToBeDeleted];
        
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        
        //If we end up with no plants in the, then prevent the user from hitting the save button.
        if([self.plantsArray count] == 0){
            [self.navigationItem.rightBarButtonItem setEnabled:NO];
        }
    }
}


#pragma mark - Picker View Delegate

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    self.selectedPlantSet = [self.existingPlantSetsArray objectAtIndex:row];
}

#pragma mark - Picker View Datasource

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return [self.existingPlantSetsArray count];
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    PlantSet *plantSet = [self.existingPlantSetsArray objectAtIndex:row];
    return plantSet.name;
}

-(UITextField *)getNameTextField
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    return (UITextField *)[cell viewWithTag:1];
}



- (IBAction)validateName:(UITextField *)sender 
{
    //If the user has entered a name then enable the Save button
    if(sender.text.length > 0){
        [self.navigationItem.rightBarButtonItem setEnabled:YES];
    }else{
        [self.navigationItem.rightBarButtonItem setEnabled:NO];
    }
}

-(void)createNewPlantSet
{
    UITextField *nameField = [self getNameTextField];
    
    //Create the PlantSet object with the use entered name and the list of plants
    [PlantSet createPlantSetWithName:nameField.text plants:self.plantsArray inContext:self.context];
    
    //Delete the plantSet from the NSUserDefaults so that we can start from fresh again.
    [PlantSet deleteAllPlantSetFromNSUserDefaults];
    [self.presentingViewController dismissModalViewControllerAnimated:YES];
}

-(void)saveToExistingPlantSet
{
    for(Plant *plant in self.plantsArray){
        [self.selectedPlantSet addPlantsObject:plant];
    }
    //Delete the plantSet from the NSUserDefaults so that we can start from fresh again.
    [PlantSet deleteAllPlantSetFromNSUserDefaults];
    [self.presentingViewController dismissModalViewControllerAnimated:YES];
}

- (IBAction)saveButtonPressed:(UIBarButtonItem *)sender 
{
    if(self.addtoExistingPlantSet == YES){
        [self saveToExistingPlantSet];
    }else{
        [self createNewPlantSet];
    }  
}

- (IBAction)cancelButtonPressed:(id)sender 
{
    [self.presentingViewController dismissModalViewControllerAnimated:YES];
}

@end
